<template>
  <el-dialog class="setting-dialog" v-model="visibility" title="表头显示属性" :append-to-body="true">
    <div class="setting-dialog-body">
      <div class="setting-dialog-body-left setting-dialog-body-content">
        <span class="title">可选择属性 · {{ optionalColumns.length }}</span>
        <div class="content">
          <el-input v-model="chooseValue" placeholder="搜索" @input="chooseSearch">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <ul class="cot">
            <li
              @click="chooseHandler(item)"
              class="cot-choose"
              v-for="(item, index) in optionalColumns"
              :key="'_setting' + index"
            >
              <span>{{ item.title }}</span>
              <span v-show="!item.isHidden" :class="{ 'cot-active': !item.isHidden }">
                <el-icon><Check /></el-icon>
              </span>
            </li>
          </ul>
        </div>
      </div>
      <div class="setting-dialog-body-right setting-dialog-body-content">
        <span class="title">已选择属性 · {{ selectedValuesUI.length }}</span>
        <div class="content">
          <el-input placeholder="搜索" v-model="selectValue" @input="selectSearch">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <div class="cot">
            <div class="li cot-title">冻结(上限3个)</div>
            <div
              class="li cot-choose cursor"
              :class="{ 'no-click': selectValue }"
              :draggable="true"
              v-for="(item, index) in selectedValuesUI.filter(itm => itm.isFixed)"
              :key="'_setting' + index"
              @dragover="dragOverHandler($event)"
              @dragenter="dragEnterHandler($event)"
              @dragstart="dragStartHandler(item)"
              @drop="dropFixedHandler(item, $event)"
            >
              <span>{{ item.title }}</span>
              <span class="cot-close" @click="chooseHandler(item)" v-show="!item.isHidden">
                <el-icon><Close /></el-icon>
              </span>
            </div>
            <div
              v-if="!selectedValues.filter(itm => itm.isFixed).length"
              class="li cot-choose cot-empty"
              :class="{ 'no-click': selectValue }"
              @dragover="dragOverHandler($event)"
              @drop="dropFixedHandler(null, $event)"
            ></div>

            <div class="li cot-title">未冻结</div>
            <div
              class="li cot-choose cursor"
              :draggable="true"
              v-for="(item, index) in selectedValuesUI.filter(itm => !itm.isFixed)"
              :key="'_setting' + index"
              :class="{ 'no-click': selectValue }"
              @dragover="dragOverHandler($event)"
              @dragstart="dragStartHandler(item)"
              @dragenter="dragEnterHandler($event)"
              @drop="dropHandler(item, $event)"
            >
              <span>{{ item.title }}</span>
              <span class="cot-close" @click="chooseHandler(item)" v-show="!item.isHidden">
                <el-icon><Close /></el-icon>
              </span>
            </div>
            <div
              class="li cot-choose cot-empty"
              :class="{ 'no-click': selectValue }"
              @dragover="dragOverHandler($event)"
              @drop="dropHandler(null, $event)"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div class="setting-dialog-body-bottom">
      <div>
        <span class="reset mr10" @click="resetHandler">重置</span>
        <span class="reset" @click="recoverHandler">恢复默认值</span>
      </div>

      <div class="setting-dialog-body-bottom-btn">
        <el-button type="text" @click="visibility = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { excludeFields } from "../../constant/index";
import { TableColumn } from "../../interface";
import { useData } from "../../hooks/useData";
import { useColumn } from "@table/hooks/useColumn";
const {
  copyTableColumns,
  tableColumns: tableColumnsUI,
  copyOriginalTableColumns,
  saveTableColumns,
  clearTableColumns
} = useData();
const { fixedStyle } = useColumn();

const visibility = defineModel("visibility", { default: false });
const tableColumns = ref<TableColumn[]>([]);
const chooseValue = ref("");
const selectValue = ref("");
const originalTableColumns = ref<TableColumn[]>([]);

// 选中的值
const selectedValues = ref<TableColumn[]>([]);
// 选中值展示UI
const selectedValuesUI = ref<TableColumn[]>([]);

// 所有字段UI
const optionalColumns = ref<TableColumn[]>([]);

const chooseHandler = (column: TableColumn) => {
  column.isHidden = !column.isHidden;
  if (column.isHidden) {
    selectedValues.value = selectedValues.value.filter(item => item.key !== column.key);
  } else {
    selectedValues.value.push(column);
  }
  if (column.isFixed) {
    column.isFixed = false;
  }
  selectedValuesUI.value = selectedValues.value;
  if (selectValue.value) {
    selectSearch(selectValue.value);
  }
};
const chooseSearch = (val: string) => {
  optionalColumns.value = originalTableColumns.value.filter(item => item.title.includes(val));
};
const selectSearch = (val: string) => {
  selectedValuesUI.value = selectedValues.value.filter(item => item.title.includes(val));
};

let source: any = null;

const exchangePosition = (item: TableColumn | null) => {
  const firstIndex = selectedValues.value.findIndex(itm => itm.key === source.key);
  const lastIndex = item ? selectedValues.value.findIndex(itm => itm.key === item.key) : 0;
  const first: any = selectedValues.value.splice(firstIndex, 1);
  if (item) {
    selectedValues.value.splice(lastIndex, 0, first[0]);
  } else {
    selectedValues.value.push(source);
  }
  selectedValuesUI.value = selectedValues.value;
};
const dragStartHandler = (item: TableColumn) => {
  source = item;
};
const dragOverHandler = (event: DragEvent) => {
  event.preventDefault();
};
const dragEnterHandler = (event: DragEvent) => {
  console.log(event);
};

const dropFixedHandler = (item: TableColumn | null, event: DragEvent) => {
  event.preventDefault();
  const len = selectedValues.value.filter(itm => itm.isFixed).length;
  if (item) {
    if (source && item.key !== source.key && len < 3) {
      source.isFixed = true;
    }
    if (source.isFixed && item.isFixed) {
      exchangePosition(item);
    }
  } else {
    source.isFixed = true;
    exchangePosition(item);
  }
};

const dropHandler = (item: TableColumn | null, event: DragEvent) => {
  event.preventDefault();
  if (item) {
    if (source && item.key !== source.key) {
      source.isFixed = false;
      exchangePosition(item);
    }
  } else {
    source.isFixed = false;
    exchangePosition(item);
  }
};

const recoverHandler = () => {
  tableColumns.value = copyTableColumns();
  tableColumns.value = tableColumns.value.filter((item: any) => !excludeFields.includes(item.type));
  originalTableColumns.value = copyOriginalTableColumns();
  originalTableColumns.value = originalTableColumns.value.filter((item: any) => !excludeFields.includes(item.type));
  optionalColumns.value = originalTableColumns.value = originalTableColumns.value.map((item: TableColumn) => {
    const obj = tableColumns.value.find((val: TableColumn) => val.key === item.key);
    if (obj) {
      item = obj;
    } else {
      item = {
        ...item,
        isHidden: true
      };
    }
    return item;
  });

  selectedValues.value = tableColumns.value.filter((item: any) => !excludeFields.includes(item.type) && !item.isHidden);
  selectedValuesUI.value = selectedValues.value;
};
const resetHandler = () => {
  clearTableColumns();
  recoverHandler();
};

const confirm = () => {
  visibility.value = false;
  const originFixedColumns = copyOriginalTableColumns().filter((item: any) => excludeFields.includes(item.type));
  tableColumnsUI.value = [...originFixedColumns, ...selectedValues.value];
  saveTableColumns();
  fixedStyle();
};

onMounted(() => {
  recoverHandler();
});
</script>
<style lang="scss" scoped>
@use "../../styles/index" as *;
.setting-table {
  box-sizing: border-box;
  width: 46px;
  height: 46px;
  line-height: 46px;
  color: #666666;
  text-align: center;
  cursor: pointer;
  background-color: #ffffff;
  border: 1px solid #eeeeee;
}
.cursor {
  cursor: grab !important;
}
.setting-dialog {
  padding-bottom: 0;
  .el-dialog__header {
    margin-bottom: 0;
  }
  &-body {
    display: flex;
    gap: 32px;
    justify-content: space-between;
    &-content {
      display: flex;
      flex: 1;
      flex-flow: column nowrap;
    }
    .title {
      display: block;
      margin-bottom: 8px;
      font-size: 14px;
      color: #666666;
    }
    .content {
      display: flex;
      flex: 1;
      flex-flow: column nowrap;
      .cot {
        height: 360px;
        padding: 8px 0;
        margin-top: 8px;
        overflow: auto;
        border: 1px solid #eeeeee;
        border-radius: 5px;
        .li,
        li {
          height: 24px;
          padding: 4px 20px;
          line-height: 24px;
          cursor: pointer;
          &:hover {
            background-color: #eeeeee;
          }
        }
        &-title {
          height: 30px !important;
          font-size: 12px !important;
          line-height: 30px !important;
          color: #aaaaaa;
          &:hover {
            background-color: #ffffff !important;
          }
        }
        &-choose {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        &-active {
          display: flex;
          align-items: center;
          height: 100%;
          color: $primary-color;
          cursor: pointer;
        }
        &-close {
          display: flex;
          align-items: center;
          height: 100%;
          pointer-events: auto;
          cursor: pointer;
          &:hover {
            color: $primary-color;
          }
        }
        &-empty {
          height: 12px !important;
          &:hover {
            background-color: transparent !important;
          }
        }
      }
    }
    &-bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 0 0;
      .reset {
        color: $primary-color;
        cursor: pointer;
      }
    }
  }
}
</style>
